
/**
 * 新零售的订单列表显示
 * 
 * 基本都是顶部信息：买家，收货人，订单号，配送方式
 * 购买商品列表，优惠信息
 * 隐藏超过一个商品的列表
 * 分页条件
 * 
 * 由于antd的原来table无法满足这种组件：
 * 因为顶部是一个无内容的table header控制
 * 内容列表是多个div嵌套一个table！
 * 基于这种需求，可以封装此组件
 * 
 */
import React, { Component, PropTypes } from 'react';
import {
    Spin,
    Pagination,
} from 'antd';
import OrderItem from './OrderItem.js';
import PageNav from './Page.js'

import noop from 'util/noop';

const defaultPagination = {
    onChange:noop,
    onShowSizeChange:noop,
}
class OrderTable extends Component {
    static propTypes = {
        columns:PropTypes.array,
        dataSource:PropTypes.array,
        pagiantion:PropTypes.object,
        header:PropTypes.oneOfType([PropTypes.node,PropTypes.element,PropTypes.func]),
        emptyText:PropTypes.oneOfType([PropTypes.string,PropTypes.func]),//无内容文字提示
        rowHeader:PropTypes.func,
        rowkey:PropTypes.oneOfType([PropTypes.string,PropTypes.func]),
        rowSelection:PropTypes.oneOfType([
            PropTypes.shape({
                selectedRowKeys:PropTypes.array,
                onChange:PropTypes.func,
                onSelect:PropTypes.func,
            }),
            PropTypes.object,
        ])
    };

    static defaultProps = {
        rowKey:'',
        emptyText:'暂无数据',
        tip:'',
        rowSelection:null,
    }
    constructor(props){
        super(props);

        this.isRenderCheckAllbox = false;

        this.state = {
            pagination:this.getDefaultPagination(props),
            selectedRowKeys:(props.rowSelection || {}).selectedRowKeys || []
        }
    }
    componentWillReceiveProps(nextProps) {
        //设置每行需渲染checkbox
        if(this.props.rowSelection != nextProps.rowSelection && nextProps.rowSelection){
            this.isRenderCheckAllbox = true;
        }

        if('pagination' in nextProps){
            this.setState((prevState) => {
                const newPagination = Object.assign({},defaultPagination,prevState.pagination,nextProps.pagination);
                newPagination.current = newPagination.current || 1;
                newPagination.pageSize = newPagination.pageSize || 10;

                return {pagination:this.hasPagination(nextProps) ? newPagination : {}}
            })
        }
        //更新选中的selectedrowkeys
        if(nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection){
            this.setState({
                selectedRowKeys:nextProps.rowSelection.selectedRowKeys
            });
        }
    }
    
    //默认分页参数
    getDefaultPagination = (props) => {
        const { pagination = {} } = props;

        return this.hasPagination(props) ? Object.assign({},defaultPagination,pagination,{
            current:pagination.defaultCurrent || pagination.current || 1,
            pageSize:pagination.defaultPageSize || pagination.pageSize || 10
        }) : {}
    }
    
    render() {
        const { 
            style, 
            className,
            tip,
            ...rest,
         } = this.props;
         let header = rest.header;
         if(typeof header === 'function'){
            header = header();
         }
         let loading = this.props.loading;
         if(typeof loading === 'boolean'){
             loading = {
                 spinning:loading
             }
         }
         const content = [
             this.getContent(rest),
             this.getEmptyContent(),
         ]

        return (
            <div className={className} style={style}>
                 <Spin {...loading} tip={tip}>
                    <div className="order-list-table">
                        <div className="order-list-table-hd">
                            {header}
                        </div>
                        <div className="order-list-table-bd">
                            {content}
                        </div>
                    </div>
                    {this.renderPagination()}
                </Spin>
            </div>
        );
    }

    getContent = (props) => {
        const { dataSource,columns, rowHeader, hideKey } = props;
        const { selectedRowKeys } = this.state;
        return dataSource.map((data,index) => {
            let checked = false;
            let disabled = false;
            if(this.isRenderCheckAllbox){
                let key = this.getRecordKey(data,index);
                checked = selectedRowKeys.includes(key)
                if('getCheckboxProps' in props.rowSelection){
                    disabled = props.rowSelection.getCheckboxProps(data).disabled || false;
                }
            }
            return (
                <OrderItem
                    key={index}
                    hideKey={hideKey}
                    eventIndex={index}
                    data={data}
                    disabled={disabled}
                    columns={columns}
                    header={rowHeader}
                    checked={checked}
                    checkAll={this.isRenderCheckAllbox}
                    onSelect={this.handleSelect}
                />
            )
        })
    }

    getRecordKey = (record, index) => {
        const { rowKey } = this.props;
        const recordKey = (typeof rowKey === 'function') ? 
            rowKey(record,index) : record[rowKey];
        return recordKey === undefined ? index : recordKey;
    }

    /**
     * 每一行数据选择回调
     */
    handleSelect = (record,selected, rowIndex) => {
        const { rowSelection = {}, dataSource } = this.props;
        let { selectedRowKeys } = this.state;
        let key = this.getRecordKey(record,rowIndex);
        if(selected){
            selectedRowKeys.push(key)
        }else{
            selectedRowKeys = selectedRowKeys.filter(rowkey => rowkey !== key)
        }
        const selectedRows = dataSource.filter((data,index)=>{
            return selectedRowKeys.indexOf(this.getRecordKey(data,index)) >= 0
        })
        //如果用户没有设置，自己处理数据
        if(rowSelection && !("selectedRowKeys" in rowSelection)){
            this.setState({selectedRowKeys});
            
        }
        rowSelection.onSelect && rowSelection.onSelect(record, selected, selectedRows);
        rowSelection.onChange && rowSelection.onChange(selectedRowKeys,selectedRows);
    }
    /**
     * 内容为空的时候提示函数
     */
    getEmptyContent = () => {
        const { emptyText,dataSource } = this.props;
        return !dataSource.length ?(
            <div key="emptyContent">
                <div className="ant-table-placeholder">
                    <span className="inline-tips">
                        <i className="anticon anticon-frown-o"></i>
                        {(typeof emptyText === 'function') ? emptyText() : emptyText}
                    </span>
                </div>
            </div>
        ) : null;
    }

    hasPagination = (props) => {
        return (props || this.props).pagiantion != false;
    }
    /**
     * 渲染分页组件
     */
    renderPagination = () => {
        
        if(!this.hasPagination()){
            return null;
        }
        let size = 'default';
        const { pagination } = this.state;
        if(pagination.size){
            size = pagination.size;
        }

        let total = pagination.total || this.props.dataSource.length;

        return total > 0 ? (
            <Pagination
                key="pagination"
                {...pagination}
                className="pull-right"
                size={size}
                total={total}
                onChange={this.handlePageChange}
                onShowSizeChange={this.handleShowSizeChange}
            />
        ) : null;
    }

    handlePageChange = (current, ... other) => {
        const  props = this.props;
        let pagination = Object.assign({},this.state.pagination);

        if(current){
            pagination.current = current;
        }else{
            pagiantion.current = pagination.current || 1;
        }
        pagination.onChange && pagination.onChange(current,...other);
        const newState = {
            pagination
        }
        //等待props的更新
        if(this.hasPagination(props) && 'current' in props.pagination){
            newState.pagination = Object.assign({},pagination,{
                    current:this.state.pagination.current
                })
        }

        this.setState(newState);
    }

    handleShowSizeChange = (current, pageSize) => {
        const pagination = this.state.pagination;
        pagination.onShowSizeChange(current, pageSize);
        const nextPagination = assign({}, pagination, { pageSize, current });
        this.setState({ pagination: nextPagination });
    }
    
}


export default OrderTable;